package com.asset.inventory.view

import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.Color
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.Gravity
import android.view.KeyEvent
import android.view.View
import android.view.WindowManager
import android.widget.TextView
import androidx.databinding.Observable
import androidx.drawerlayout.widget.DrawerLayout
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.asset.inventory.BR
import com.asset.inventory.R
import com.asset.inventory.adapter.ProductAdapter
import com.asset.inventory.base.BaseActivity
import com.asset.inventory.base.BaseApp
import com.asset.inventory.constant.InventoryState
import com.asset.inventory.databinding.ActivityAssetInventoryDetailBinding
import com.asset.inventory.kt.hideSoftKeyboard
import com.asset.inventory.kt.logE
import com.asset.inventory.kt.toast
import com.asset.inventory.manager.RfidManager
import com.asset.inventory.manager.ScanReader
import com.asset.inventory.model.TaskBean
import com.asset.inventory.model.TaskDetailBean
import com.asset.inventory.viewModel.AssetInventoryDetailViewModel

/**
 *    @author : sibb
 *    date   : 21-3-16
 *    desc   : 资产详情页面
 */
class AssetInventoryDetailActivity : BaseActivity<AssetInventoryDetailViewModel, ActivityAssetInventoryDetailBinding>() {
    private val TAG = "AssetInventoryDetailAct"
    private lateinit var scanReader: ScanReader
    private lateinit var back: TextView
    private lateinit var exit: TextView
    private var result = ""

    private var STATE_DEVICE = 0

    private val OFF = 0

    private val SCAN_ON = 1

    private val RFID_ON = 2

    private var title: TextView? = null

    private var taskId = 0L

    private lateinit var detailSelected: TaskDetailBean.Detail

    private val mProductList = mutableListOf<TaskDetailBean.Detail>()
    private val mProductTypeList = mutableListOf<TaskDetailBean.Detail>()

    private val mWaiCommitId = mutableListOf<Long>()
    private val mScanCode = mutableListOf<String>()


    private var LIST_DATA_TYPE = 0

    private val LIST_ALL = 0

    private val LIST_WAIT = 1

    private val LIST_FINISH = 2

    private val productAdapter: ProductAdapter by lazy {
        ProductAdapter(mProductTypeList, object : ProductAdapter.OnItemListener {
            override fun onItemClickEvent(position: Int) {
                detailSelected = mProductTypeList[position]
                updateRightMenuUI(detailSelected)
                //todo 设置抽屉里资产详细信息
                binding.rightMenu.openDrawer(Gravity.RIGHT)
            }

            override fun onModifyStatusEvent(position: Int) {
                val dialog = ModifyStateDialog(position, object : ModifyStateDialog.onStateSelectedListener {
                    override fun onChange(position: Int, state: String) {
//                        mProductTypeList[position].dutyResultStatus = state
//                        productAdapter.notifyDataSetChanged()

                        if (mWaiCommitId.contains(mProductTypeList[position].id)) {
                            mWaiCommitId.remove(mProductTypeList[position].id)
                            if (mWaiCommitId.size > 0) {
                                binding.waitCommitCount.visibility = View.VISIBLE
                                binding.waitCommitCount.text = "${mWaiCommitId.size}"
                            } else {
                                binding.waitCommitCount.visibility = View.GONE
                            }
                        }
                        mViewModel.uploadState(mProductTypeList[position].id, state)

                        //更新全数据中状态
                        for (p in mProductList) {
                            if (p.id == mProductTypeList[position].id) {
                                p.dutyResultStatus = state
                            }
                        }
                        notifyList()

                    }

                })
                dialog.showNow(supportFragmentManager, "modifyDialog")
            }
        })
    }


    override fun getLayoutId(): Int = R.layout.activity_asset_inventory_detail

    override fun initVariableId(): Int = BR.assetInventoryDetailViewModel

    override fun initViewModel(): Class<AssetInventoryDetailViewModel> = AssetInventoryDetailViewModel::class.java

    //接收返回数据
    private val resultReceiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val barcode = intent.getByteArrayExtra(ScanReader.SCAN_RESULT)
            if (barcode != null) {
                var sb = StringBuilder().apply {
                    append(String(barcode))
//                    append("\n")
                }
                result = sb.toString()
//                toast("扫描到${result}")
//                testScan()

                handlerDeviceScanData(result)
            }
        }
    }

    override fun initView() {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        title = binding.bar.findViewById(R.id.title)
        back = binding.bar.findViewById(R.id.left)
        exit = binding.bar.findViewById(R.id.right)
        back.visibility = View.VISIBLE
        back.text = "返回"

        binding.rightMenu.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);//关闭手势滑动

        binding.productList.layoutManager = LinearLayoutManager(this)
        binding.productList.adapter = productAdapter


        val filter = IntentFilter()
        filter.addAction(ScanReader.ACTION_SCAN_RESULT)
        registerReceiver(resultReceiver, filter)
        scanReader = ScanReader(this)
        scanReader.init()

        binding.commit.visibility = View.VISIBLE
        binding.commitLine.visibility = View.VISIBLE


    }

    fun updateRightMenuUI(detail: TaskDetailBean.Detail) {
        binding.serverName.text = detailSelected.name
        binding.code.text = "资产编号：${detailSelected.code}"
        if (!TextUtils.isEmpty(detailSelected.computerRoom)) {
            binding.computerRoom.text = "机房：${detailSelected.computerRoom}"
        } else {
            binding.computerRoom.text = "机房：--"
        }
        if (!TextUtils.isEmpty(detailSelected.cabinet)) {
            binding.cabinet.text = "机柜：${detailSelected.cabinet}"
        } else {
            binding.cabinet.text = "机柜：--"
        }
        if (BaseApp.instance.isOnlineModel) {
            binding.locationName.text = "位置：${detailSelected.locationName}"
            binding.orgName.text = "使用部门：${detailSelected.orgName}"
            binding.userName.text = "使用人：${detailSelected.userName}"


        } else {
            if (TextUtils.isEmpty(detail.updateLocationName)) {
                binding.locationName.text = "位置：${detailSelected.locationName}"
            } else {
                binding.locationName.text = "位置：${detailSelected.updateLocationName}"
            }

            if (TextUtils.isEmpty(detail.updateOrgName)) {
                binding.orgName.text = "使用部门：${detailSelected.orgName}"
            } else {
                binding.orgName.text = "使用部门：${detailSelected.updateOrgName}"
            }

            if (TextUtils.isEmpty(detail.updateUserName)) {
                binding.userName.text = "使用人：${detailSelected.userName}"
            } else {
                binding.userName.text = "使用人：${detailSelected.updateUserName}"
            }
        }

    }

    override fun initListener() {
        super.initListener()

        exit.setOnClickListener {
//            testScan()
            BaseApp.instance.finishAllActivity()
            startActivity(Intent(this, LoginActivity::class.java))
        }
        back.setOnClickListener {
            binding.rightMenu.closeDrawer(Gravity.RIGHT)
            finish()
        }

        binding.waitLayout.setOnClickListener {
            //设置列表显示类型
            if (LIST_DATA_TYPE != LIST_WAIT) {
                LIST_DATA_TYPE = LIST_WAIT
            } else {
                LIST_DATA_TYPE = LIST_ALL
            }
            //刷新列表
            notifyList()
        }

        binding.finishLayout.setOnClickListener {
            //设置列表显示类型
            if (LIST_DATA_TYPE != LIST_FINISH) {
                LIST_DATA_TYPE = LIST_FINISH
            } else {
                LIST_DATA_TYPE = LIST_ALL
            }
            //刷新列表
            notifyList()

        }

        binding.commit.setOnClickListener {
            if (mWaiCommitId.size == 0) {
                toast("无提交数据")
                return@setOnClickListener
            }
            if (BaseApp.instance.isOnlineModel) {
                //提交数据到服务器
                mViewModel.commitDataToServer(mWaiCommitId)
            } else {
                mViewModel.saveDatasToSD(mWaiCommitId, InventoryState.STATE_EQUALITY)
            }
        }

        mViewModel.isStartScan.addOnPropertyChangedCallback(object : Observable.OnPropertyChangedCallback() {
            override fun onPropertyChanged(sender: Observable?, propertyId: Int) {
                if (mViewModel.isStartScan.get()!!) {
                    STATE_DEVICE = SCAN_ON
                    isScanEvent = true
                } else {
                    isScanEvent = false
                }
            }
        })
        mViewModel.isReadRfid.addOnPropertyChangedCallback(object : Observable.OnPropertyChangedCallback() {
            override fun onPropertyChanged(sender: Observable?, propertyId: Int) {
                if (mViewModel.isReadRfid.get()!!) {
                    //开始rfid
                    toast(resources.getString(R.string.start_rfid))
                    STATE_DEVICE = RFID_ON
                    isReadRfidEvent = true
                    RfidManager.instance.sendReadEpcCmd()
                } else {
                    //关闭rfid
                    toast(resources.getString(R.string.cloes_rfid))
                    isReadRfidEvent = false
                    RfidManager.instance.sendStopCmd()
                }
            }
        })

        binding.inputData.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(p0: Editable?) {

            }

            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                if (isScanEvent) {
                    isScanEvent = false
                    result = binding.inputData.text.toString().replace("(\\\r\\\n|\\\r|\\\n|\\\n\\\r)", "")
                    binding.inputData.setText("")
                    handlerDeviceScanData(result)
//                    testScan()

                }
            }
        })

        mViewModel.observerData().observe(this, Observer {
            if (mProductList.size > 0) {
                mProductList.clear()
            }
            mProductList.addAll(it)
            notifyList()
            updateTaskCount()
        })

        RfidManager.instance.epcLiveData.observe(this, Observer {
            "rfid扫描到---------${it.epc}".logE()
            it.epc = if (it.epc.endsWith("X")) it.epc.substring(0, it.epc.length - 1) else it.epc
//            testScan()
            if (!mScanCode.contains(it.epc)) {
                mScanCode.add(it.epc)
                handlerDeviceScanData(it.epc)
                if (mScanCode.size > 0) {
                    binding.scanCount.visibility = View.VISIBLE
                    binding.scanCount.text = "${mScanCode.size}"
                } else {
                    binding.scanCount.visibility = View.GONE
                }

            }

        })

        binding.modifyAssets.setOnClickListener {
            val intent = Intent(this, ModifyAssetsActivity::class.java)
            val bundle = Bundle()
            bundle.putSerializable("TASK_DETAIL", detailSelected)
            bundle.putLong("TASK_ID", taskId)
            intent.putExtras(bundle)
            startActivityForResult(intent, 4000)
        }

        mViewModel.isModifySuccess.observe(this, Observer {
            if (it) {
                toast("盘点状态修改成功")
                if (BaseApp.instance.isOnlineModel) {
                    updateTaskCount()
                } else {
                    binding.waitCount.text = "${mViewModel.getOffWaitCount()}"
                    binding.finishCount.text = "${mViewModel.getOffFinishCount()}"
                }

            } else {
                toast("盘点状态修改失败")
            }
        })

        mViewModel.observerCommitStatus().observe(this, Observer {
            if (it) {
                toast("同步数据成功")
                mWaiCommitId.clear()
                binding.waitCommitCount.text = "0"
                binding.waitCommitCount.visibility = View.GONE
            } else {
                toast("同步数据失败")
            }
        })

        mViewModel.loadingLiveData().observe(this, Observer {
            if(it){
                showLoading()
            }else{
                closeLoading()
            }
        })

        title?.setOnClickListener {
//            for(p in mProductList){
//                if(p.dutyResultStatus == InventoryState.STATE_WAIT || p.dutyResultStatus == InventoryState.STATE_LOSS){
//                    p.code?.let { it -> handlerDeviceScanData(it) }
//                    return@setOnClickListener
//                }
//            }
        }

    }

    @SuppressLint("ResourceAsColor")
    fun notifyList() {
        mProductTypeList.clear()
        if (LIST_DATA_TYPE == LIST_ALL) {
            binding.finishLayout.setBackgroundColor(Color.parseColor("#FFFFFF"))
            binding.waitLayout.setBackgroundColor(Color.parseColor("#FFFFFF"))
            binding.finishText.setTextColor(Color.parseColor("#000000"))
            binding.waitText.setTextColor(Color.parseColor("#000000"))
            binding.finishCount.setTextColor(Color.parseColor("#000000"))
            binding.waitCount.setTextColor(Color.parseColor("#000000"))
            mProductTypeList.addAll(mProductList)
        } else {
            for (p in mProductList) {
                if (LIST_DATA_TYPE == LIST_FINISH) {
                    binding.finishLayout.setBackgroundColor(Color.parseColor("#F0F0F0"))
                    binding.waitLayout.setBackgroundColor(Color.parseColor("#FFFFFF"))
//                    binding.finishText.setTextColor(Color.parseColor("#FFFFFF"))
//                    binding.waitText.setTextColor(Color.parseColor("#000000"))
//                    binding.finishCount.setTextColor(Color.parseColor("#FFFFFF"))
//                    binding.waitCount.setTextColor(Color.parseColor("#000000"))
                    if (p.dutyResultStatus == InventoryState.STATE_EQUALITY || p.dutyResultStatus == InventoryState.STATE_LOSS) {
                        mProductTypeList.add(p)
                    }
                } else if (LIST_DATA_TYPE == LIST_WAIT) {
                    binding.finishLayout.setBackgroundColor(Color.parseColor("#FFFFFF"))
                    binding.waitLayout.setBackgroundColor(Color.parseColor("#F0F0F0"))
//                    binding.finishText.setTextColor(Color.parseColor("#000000"))
//                    binding.waitText.setTextColor(Color.parseColor("#FFFFFF"))
//                    binding.finishCount.setTextColor(Color.parseColor("#000000"))
//                    binding.waitCount.setTextColor(Color.parseColor("#FFFFFF"))
                    if (p.dutyResultStatus == InventoryState.STATE_WAIT) {
                        mProductTypeList.add(p)
                    }
                }
            }
        }
        productAdapter.notifyDataSetChanged()


    }


    override fun onStart() {
        super.onStart()
        val task: TaskBean.Task = intent.extras?.getSerializable("TASK_DATA") as TaskBean.Task
        task.let {
            taskId = task.id
            mViewModel.setTaskId(taskId)
            title?.text = it.inventoryPlanName
            binding.createPerson.text = "创建人：${it.inventoryPlanCreateUser}"
            binding.startTime.text = "开始时间：${it.inventoryPlanStartDate}"
            binding.total.text = "盘点总数：${it.dutyResultCount}"
            binding.endTime.text = "结束日期：${it.inventoryPlanEndDate}"
            binding.waitCount.text = "${it.dutyResultWaitCount}"
            binding.finishCount.text = "${it.dutyResultDoneCount}"
            mViewModel.getTaskDetail(task.id!!)
        }
        RfidManager.instance.setPower(1)
    }

    override fun onResume() {
        super.onResume()
        mScanCode.clear()
        binding.scanCount.visibility = View.GONE
    }

    override fun onStop() {
        super.onStop()
        RfidManager.instance.setPower(0)
    }

    var isScanEvent = false
    var isReadRfidEvent = false
    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(resultReceiver)
        scanReader.closeScan()
        RfidManager.instance.sendStopCmd()
        STATE_DEVICE = OFF
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (event?.keyCode == KeyEvent.KEYCODE_F1) {
            if (STATE_DEVICE == SCAN_ON) {
                isScanEvent = true
            } else if (STATE_DEVICE == RFID_ON) {
                if (isReadRfidEvent) {
                    mViewModel.isReadRfid.set(false)
                } else {
                    mViewModel.isReadRfid.set(true)
                }
            }

            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == 4000 && resultCode == RESULT_OK) {
            val detailBean = data?.extras?.getSerializable("TASK_DETAIL") as TaskDetailBean.Detail
            detailBean.let {
                binding.locationName.text = "位置：${it.updateLocationName}"
                binding.orgName.text = "使用部门：${it.updateOrgName}"
                binding.userName.text = "使用人：${it.updateUserName}"
            }
        }
        super.onActivityResult(requestCode, resultCode, data)
    }

    /**
     * 处理设备扫描结果
     */
    private fun handlerDeviceScanData(code: String) {
        for (product in mProductList) {
            if (product.code == code && product.dutyResultStatus != InventoryState.STATE_EQUALITY) {
                // toast("扫描到${code}")
                product.dutyResultStatus = InventoryState.STATE_EQUALITY
                notifyList()
                if (!mWaiCommitId.contains(product.id)) {
                    mWaiCommitId.add(product.id)
                }
            }
        }
        if (mWaiCommitId.size > 0) {
            binding.waitCommitCount.visibility = View.VISIBLE
            binding.waitCommitCount.text = "${mWaiCommitId.size}"
        } else {
            binding.waitCommitCount.visibility = View.GONE
        }
        updateTaskCount()
    }

    /**
     * 更新待盘点已盘点数量
     */
    private fun updateTaskCount() {
        val map = getCount()
        binding.waitCount.text = "${map["waitCount"]}"
        binding.finishCount.text = "${map["finished"]}"
    }


    /**
     * 获取待盘点已经盘点的数量
     */
    fun getCount(): HashMap<String, Int> {
        var finishedCount = 0
        var waitCount = 0
        for (p in mProductList) {
            if (p.dutyResultStatus == InventoryState.STATE_EQUALITY || p.dutyResultStatus == InventoryState.STATE_LOSS) {
                finishedCount++
            } else if (p.dutyResultStatus == InventoryState.STATE_WAIT) {
                waitCount++
            }
        }
        val countMap = HashMap<String, Int>()
        countMap.put("finished", finishedCount)
        countMap.put("waitCount", waitCount)
        return countMap
    }

    fun testScan() {
        out@ for (p in mProductList) {
            if (p.dutyResultStatus == InventoryState.STATE_WAIT || p.dutyResultStatus == InventoryState.STATE_LOSS) {
                p.code?.let { it ->
                    if (!mScanCode.contains(it)) {
                        mScanCode.add(it)
                        handlerDeviceScanData(it)
                        if (mScanCode.size > 0) {
                            binding.scanCount.visibility = View.VISIBLE
                            binding.scanCount.text = "${mScanCode.size}"
                        } else {
                            binding.scanCount.visibility = View.GONE
                        }

                    }
                }
                break@out
            }
        }
    }


    fun closeLoading(){
        binding.loading.visibility = View.GONE
        binding.avi.smoothToHide()
    }


    fun showLoading(){
        binding.loading.visibility = View.VISIBLE
        binding.avi.smoothToShow()
    }

}